package cn.stylefeng.roses.kernel.ca.server.core.token;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.stylefeng.roses.kernel.ca.api.CaLoginUserEncryptApi;
import cn.stylefeng.roses.kernel.ca.api.pojo.SsoTokenBuild;
import com.alibaba.fastjson.JSON;

/**
 * AES方式加密解密登陆用户
 * <p>
 * AES加密的秘钥必须是16者32个字节的秘钥
 *
 * @author fengshuonan
 * @date 2021/1/21 19:17
 */
public class AesCaLoginUserEncrypt implements CaLoginUserEncryptApi {

    /**
     * 加密解密的秘钥
     */
    private final String secret;

    public AesCaLoginUserEncrypt(String secret) {
        this.secret = secret;
    }

    @Override
    public String encrypt(SsoTokenBuild caLoginUser) {
        AES aesUtil = SecureUtil.aes(Base64.decode(secret));
        String loginUserJson = JSON.toJSONString(caLoginUser);
        return aesUtil.encryptBase64(loginUserJson);
    }

    @Override
    public SsoTokenBuild decrypt(String encryptStr) {
        AES aesUtil = SecureUtil.aes(Base64.decode(secret));
        String loginUserJson = aesUtil.decryptStr(encryptStr, CharsetUtil.CHARSET_UTF_8);
        return JSON.parseObject(loginUserJson, SsoTokenBuild.class);
    }

}
